package opt.power.springdemo.user.controller;

import opt.power.springdemo.exception.ResourceNotFoundException;
import opt.power.springdemo.user.mapper.model.User;
import opt.power.springdemo.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * @author xuliduo
 * @date 2017/11/16
 * @description class UserController
 */
@RestController
@RequestMapping("/api/user")
@EnableAutoConfiguration
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(final UserService userService) {
        this.userService = userService;
    }

    /**
     * 处理 service抛出的ResourceNotFoundException
     * ResourceNotFoundException -> 404
     */
    @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
    @ExceptionHandler(ResourceNotFoundException.class)
    public void notFound() {
    }

    /**
     * 返回所有的用户
     *
     * @return users
     */
    @GetMapping("")
    public Flux<User> list() {
        return this.userService.list();
    }

    /**
     * 通过 id 查找用户
     *
     * @param id user id
     * @return user or 404
     */
    @GetMapping("/{id}")
    public Mono<User> getById(@PathVariable("id") final Long id) {
        return this.userService.getById(id);
    }

    /**
     * 创建对象
     *
     * @param users users
     * @return users
     */
    @PostMapping("")
    public Flux<User> create(@RequestBody final List<User> users) {
        return this.userService.createOrUpdate(users);
    }

    /**
     * 更新对象
     *
     * @param id   user id
     * @param user user
     * @return user
     */
    @PutMapping("/{id}")
    public Mono<User> update(@PathVariable("id") final Long id, @RequestBody final User user) {
        Objects.requireNonNull(user);
        user.setId(id);
        return this.userService.createOrUpdate(user);
    }

    /**
     * 删除对象
     *
     * @param id user id
     * @return null
     */
    @DeleteMapping("/{id}")
    public Mono<User> delete(@PathVariable("id") final Long id) {
        return this.userService.delete(id);
    }
}
